﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace PortalWeb.Common.Extensions
{
    public static class StringExtension
    {
        public static string ToUnmanagedCharArray(this string str, int length)
        {
            string _ReturnString = "";
            try
            {
                if (str.Length > length)
                {
                    return str.Substring(0, length);
                }
                _ReturnString = str;
            }
            catch (Exception)
            {
            }
            return _ReturnString;
        }

        public static string[] SplitBy(this string str, params string[] separator)
        {
            if (str.IsNullOrEmpty())
            {
                return new string[0];
            }
            if (separator.Length == 0)
            {
                return new string[] { str };
            }
            return str.Split(separator, StringSplitOptions.RemoveEmptyEntries);
        }


        public static string[] SplitBy(this string str, params char[] separator)
        {
            if (str.IsNullOrEmpty())
            {
                return new string[0];
            }
            if (separator.Length == 0)
            {
                return new string[] { str };
            }
            return str.Split(separator, StringSplitOptions.RemoveEmptyEntries);
        }

        public static T DeserializeTo<T>(this string str) where T : class
        {
            try
            {
                DataContractSerializer ser = new DataContractSerializer(typeof(T));
                StringReader reader = new StringReader(str);
                XmlTextReader xmlReader = new XmlTextReader(reader);
                return (ser.ReadObject(xmlReader) as T);
            }
            catch
            {
                return default(T);
            }
        }


        public static void AppendFormatLine(this StringBuilder sb, string format, params object[] args)
        {
            if (sb != null)
            {
                sb.AppendFormat(format, args);
                sb.AppendLine();
            }
        }

        public static StringBuilder AppendLine(this StringBuilder sb, string format, params object[] args)
        {
            sb.AppendFormat(format, args);
            sb.AppendLine();
            return sb;
        }
    }
}
